<?php
/*
Plugin Name: Featured Listings
Plugin URI: http://www.realivent.com
Description: Displays your features listings (Active, Pending and Sold) from Realivent.com
Version: 1.0
License: GPL
Author: Realivent Corporation
Author URI: http://www.realivent.com
Contributors: Bhavin Patel, Ken Bui
==============================================================================
*/

function featured_listings_admin_menu() {
	if (function_exists('add_options_page')) {
		add_options_page('FL Options Page', 'Featured Listings', 8, basename(__FILE__), 'fl_subpanel');
	}
}

function fl_subpanel()
{
	$blogname = $_SERVER['HTTP_HOST'];
	$blogname = str_replace(".","_",$blogname);
	$current_user = wp_get_current_user();
	$user_id = $current_user->ID;

	if(!get_post(get_option('Featured_Listing_Page_ID')))
	{
		//The page has been deleted so let's remove all the details
		delete_option('realivent_SPW_listing');
		delete_option('realivent_show_actives');
		delete_option('realivent_show_pendings');
		delete_option('realivent_show_solds');
		delete_option('Featured_Listing_Page_Title');
		delete_option('Featured_Listing_Page_ID');
	}


	//this controls what user listings are displayed
	if(isset($_POST['submitusername']))
	{
		update_option('fl_realivent_username', $_POST['fl_realivent_username']);
	}



	if(isset($_POST['submit']))
	{
		//echo 'hit1';
		//if the update button have been clicked and there is a username, go ahead an either update or
		//create the featured listing page.
		if(isset($_POST['ptitle']))
		{

			//echo get_option('Featured_Listing_Page_ID');
			//if(get_post(get_option('Featured_Listing_Page_ID')))
			//{
			$_POST['post_type'] = 'page';
			$_POST['post_content'] = '<!--Featured Listings-->';
			$_POST['post_author'] = $user_id;
			$_POST['post_status'] = 'publish';;
			$_POST['post_title'] = $_POST['ptitle'];

			if(get_option('Featured_Listing_Page_ID'))
			$_POST['ID'] = get_option('Featured_Listing_Page_ID');

			$post_ID = wp_update_post($_POST);
			update_meta(get_option('Featured_Listing_Page_ID'), '_wp_page_template', $_POST['page_template']);
			update_option('Featured_Listing_Page_ID', $post_ID);





		}
		update_option('realivent_SPW_listing', $_POST['listing']);
		update_option('Featured_Listing_Page_Title', $_POST['ptitle']);
		update_option('google_api', $_POST['google_api']);


		if(isset($_POST['actives']))
		update_option('realivent_show_actives', 'true');
		else
		update_option('realivent_show_actives', 'false');

		if(isset($_POST['pendings']))
		update_option('realivent_show_pendings', 'true');
		else
		update_option('realivent_show_pendings', 'false');

		if(isset($_POST['solds']))
		update_option('realivent_show_solds', 'true');
		else
		update_option('realivent_show_solds', 'false');

		echo "<meta http-equiv=refresh content=0;URL=?page=featured_listings_plugin.php&updated=true>";
		die;
	}


?>
 <div class='wrap'>

  <fieldset name="set1">
  <?
  if(!get_post(get_option('Featured_Listing_Page_ID')))
  {
	  ?>
	   This will add your listings to your blog. We pull the data from Realivent.com, so you will need a Realivent account, and you need to add your listing details to Realivent.com.
  Once you add your listing to Realivent.com you will be able to create all your marketing material including print, internet, and email.<br />

	  <?
  }
  else
  {
  	$array = get_post(get_option('Featured_Listing_Page_ID'));
  	echo '<div style="padding:5px; font-size:14px;">View the Featured Listing Page: <a href="'.$array->guid.'">'.$array->guid.'</a</div>';
  }
	 ?>


<br />

	</fieldset>
   <h2>Realivent Account Settings</h2>
     <fieldset name="set1">


	Realivent Username :
	<form method="post" name=formusername>
		<input name="fl_realivent_username" type="text" value="<?= get_option('fl_realivent_username') ?>"> This plugin will grab listings for this account
		<br /><input type="submit" name="submitusername" value="<?php _e('Update Realivent Username', 'Localization name')?>" />
	</form>
	 </fieldset>
	 <fieldset>
	<?
	$check='';
	$check = get_option('fl_realivent_username');
	if(!$check)
	{
		echo "<div style='color:#cc0000;'>Once you set your realivent account name you will see all the configs</div>";
	}
	?>
	</fieldset>
	 <form method="post" name=formpage>
	  <!--<div>
	You need to get the google map api to map the properties. <a href=http://www.google.com/apis/maps/>Get A google map key here</a><br />
	Google Maps API Key:

	<input name="google_api" style="width:99%;" type="text" value="<?//= get_option('google_api') ?>" /><br />
	<br />
	</div>-->
	<?
	if($check)
	{
	?>
	<br />
<?
if(!get_post(get_option('Featured_Listing_Page_ID')))
{
?>
	 <h2>Create the Featured Listing Page</h2>
<?
}else{
?>
	 <h2>Update the Featured Listing Page</h2>
<?
}
?>

	 <div style="font-size:16px; color:#FF3300"><strong>Make this a Single Property Website</strong></div>
	 <br />If you leave this blank, all your listings will be displayed.
     <fieldset name="set1">
	 <?
	 if(get_option('fl_realivent_username')!='')
	 {
	 	//$listings = simplexml_load_file("http://realivent.com/services/get_agent_listings_xml.php?username=".get_option('fl_realivent_username'));

	 	$fields="";

	 	$lidata = getContentUsingCurl("http://realivent.com/services/get_agent_listings_xml.php?username=".get_option('fl_realivent_username'),$fields);

	 	$pc =& new xmlParser();
	 	$pc->parse($lidata);
	 	$opt = $pc->output;
	 	$listings = getSimpleArray($opt);


		 ?>

		 <table width="600" border="0">

		  <tr>
			<td width='200' align="right">Choose Listing:</td>
			<td>

			<select name="listing">
				<option value=''>---Do not Use---</option>
					<?
					foreach($listings as $listing)
					{
						?>
						<option value='<?php echo $listing['OID'] ?>'><?php echo $listing['STREETNUM']." ".$listing[STREETDIR]." ".$listing['STREETNAME']." ".$listing['STREETSUFFIX'] .", ".$listing['CITY']." ".$listing['STATE']  ?> | <?php echo $listing['LISTSTATUS'] ?> </option>
						<?
					}
						?>
				</select>

		<script language="JavaScript" type="text/javascript">
		var cval = '<?php echo get_option('realivent_SPW_listing'); ?>';
		for(i=0;i<document.forms[1].listing.options.length;i++)
		if(document.forms[1].listing.options[i].value==cval)
		document.forms[1].listing.options[i].selected=true;
		</script>

			</td>
		  </tr>
		</table>

		 </fieldset>
		 <?
	 }
	 else
	 {
			?>
			You have to enter your Realivent Username to create a Single Property Website.
			<?
	 }
		 ?>


     <!--<fieldset name="set2">
     Realivent Password :
	 <input name="upass" type="password" value="">
     </fieldset>-->
    <div style="font-size:16px; color:#FF3300"><strong>Display Settings</strong></div>


	 <strong>This controls the way your page will display listings.</strong>
	 <br />
	 <table width="600" border="0">
	 		<tr>
				<td colspan="2">Page title is visible in the page menu</td>
			</tr>
		  <tr>
			<td width="100" nowrap="nowrap" align="right">Page Title:</td>
			<td><input name="ptitle" type="text" value="<?= get_option('Featured_Listing_Page_Title') ?>"></td>
		  </tr>
		  <tr>
				<td colspan="2">Some themes have more then one page template. We suggest using a template with no sidebar so the listing details are not forced into
				a small space. A full page template is the best</td>
			</tr>
		  <tr>
		<td width='100' nowrap="nowrap" align="right">Available Page Templates:</td>
		<td>
		 <?php if ( 0 != count( get_page_templates() ) ) { ?>
			<fieldset id="pagetemplate" class="dbx-box">

			 <select name="page_template">
					<option value='default'><?php _e('Default Template'); ?></option>
					<?php page_template_dropdown($post->page_template); ?>
					</select>

		<script language="JavaScript" type="text/javascript">
		var cval = '<?php echo get_post_meta(get_option('Featured_Listing_Page_ID'),"_wp_page_template", true); ?>';
		for(i=0;i<document.forms[1].page_template.options.length;i++)
		if(document.forms[1].page_template.options[i].value==cval)
		document.forms[1].page_template.options[i].selected=true;
		</script>

			</fieldset>
			<?php } ?>
		</td>
	  </tr>
		</table>
	 <strong>What type of listings do you want to display?</strong>
     <fieldset name="set1">
	 <?
	 if(get_option('realivent_show_actives')==='false')
	 {
		 ?>
		<input name="actives" type="checkbox" value='Actives'>Actives
		<?
	 }
	 else
	 {
		 ?>
		<input name="actives" type="checkbox" value='Actives' checked="checked">Actives
		<?
	 }
		?>
     </fieldset>
	    <fieldset name="set2">
		 <?
		 if(get_option('realivent_show_pendings')==='false')
		 {
		 ?>
		<input name="pendings" type="checkbox" value='Pendings'>Pendings
		<?
		 }
		 else
		 {
		 ?>
		 <input name="pendings" type="checkbox" value='Pendings' checked="checked">Pendings
		 <?
		 }
		 ?>
		 </fieldset>   <fieldset name="set2">
		  <?
		  if(get_option('realivent_show_solds')==='false')
		  {
		 ?>
		<input name="solds" type="checkbox" value='Solds'>Solds
		 <?
		  }
		  else
		  {
		 ?>
		 <input name="solds" type="checkbox" value='Solds' checked="checked">Solds
		  <?
		  }
		 ?>
     </fieldset>

<div class="submit" style="text-align:left">
<br />
<?
if(!get_post(get_option('Featured_Listing_Page_ID')))
{
?>
  <input type="submit" name="submit" value="<?php _e('Create a Featured Listing Page', 'Localization name')?>" /></div>
  <?
}else{
  ?>
  <input type="submit" name="submit" value="<?php _e('Update Featured Listing Page', 'Localization name')?>" /></div>
  <?
}
  ?>
  </form>
 </div>
 <div class='wrap'>
  <?
	}
	?>
 <?php
 $ch = curl_init("http://realivent.com/advert/featured_listings.php");
 $fields = array(
 "username" => $username,
 "password" => $password
 );
 $sendheaders = array("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
 curl_setopt($ch, CURLOPT_NOBODY, 0); // set to 1 to eliminate body info from response
 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
 curl_setopt($ch, CURLOPT_HTTPHEADER, $sendheaders);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // use HTTP POST to send form data

 $resp = curl_exec($ch); //execute post and get results
 curl_close ($ch);
 echo $resp;
?>
</div>
<?
}

function fl_callback( $content )
{

	/* Check to see if the phplist form comment is found in the incoming content
	If no match then return the content as is */
	if(! preg_match('|<!--Featured Listings-->|', $content)) {
		return $content;
	}
	if((get_option('realivent_SPW_listing')!='') && (!isset($_GET['all'])))
	{
		//echo "listing_id= No GET"; echo "<br>";

		return str_replace('<!--Featured Listings-->', get_featured_listings_details(get_option('realivent_SPW_listing')), $content);
	}
	//$string
	if(isset($_GET['listing_id']))
	{
		//echo "listing_id=";
		//echo $_GET['listing_id'];
		//echo "listing_id= GET"; echo "<br>";

		return str_replace('<!--Featured Listings-->', get_featured_listings_details($_GET['listing_id']), $content);
	}
	else
	{
		//echo "no listing_id";
		return str_replace('<!--Featured Listings-->', get_featured_listings(), $content);
	}

}

include 'clsxmlparser.php';
function get_featured_listings()
{

	//$fl_url = "http://realivent.com/services/get_featured_listings_xml.php?username=".get_option('fl_realivent_username')."&actives=".get_option('realivent_show_actives')."&pendings=".get_option('realivent_show_pendings')."&solds=".get_option('realivent_show_solds');
	//
	//echo "fl_url=";
	//echo $fl_url;

	//$listings = simplexml_load_file("http://realivent.com/services/get_featured_listings_xml.php?username=".get_option('fl_realivent_username')."&actives=".get_option('realivent_show_actives')."&pendings=".get_option('realivent_show_pendings')."&solds=".get_option('realivent_show_solds'));
	$fields="";

	$listdata = getContentUsingCurl("http://realivent.com/services/get_featured_listings_xml.php?username=".get_option('fl_realivent_username')."&actives=".get_option('realivent_show_actives')."&pendings=".get_option('realivent_show_pendings')."&solds=".get_option('realivent_show_solds'),$fields);

	$p =& new xmlParser();
	$p->parse($listdata);
	$opt = $p->output;
	$listings = getSimpleArray($opt);



?>

<div style="float:left; width:400px; border:0px solid black;">
<?
for($i=0;$i<sizeof($listings);$i++)
{
	$listing = $listings[$i];
		?>
		<table width="90%"  border="0" cellspacing="0" cellpadding="0" style="padding-top:10px; ">
			<tr>
				<td colspan="2"><div style="font-size:18px; color:#333333; padding:10px 0px 0px 0px; "><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing['STREETNAME']." ".$listing['STREETSUFFIX'].", ".$listing['CITY']." ".$listing['STATE'] ?></div></td>
			</tr>
			<tr>
				<td colspan="2"><div style="font-size:12px; color:#333333; padding:0px 0px 5px 0px; "><?php echo $listing[TITLE] ?></div></td>
			</tr>
			  <tr>
			  	<? $image = ($listing['IMAGE'] != '')? "http://realivent.com/listing_images/t_".$listing['IMAGE'] : "http://realivent.com/listing_images/nia_thumb.gif" ?>
				<td width='120'><a href="?all=true&amp;listing_id=<?php echo $listing['OID'] ?>"><img style="border:1px solid black;" src="<? echo $image ?>" alt="" /></a></td>

				<td width="*" valign="top">
				<div style="padding-top:5px;">
					<div style="float:left; padding-right:10px;"><?php echo $listing['BEDS'] ?> Beds | </div>
					<div style="float:left; padding-right:10px; "><?php echo $listing['BATHSTOTAL'] ?> Baths</div>
					<div style="clear:left"></div>
					<div style="float:left; padding-right:10px; "><?php echo number_format($listing['SQFTTOTAL'], 0) ?> SQFT | </div>
					<div style="float:left; padding-right:10px; ">Covered Parking: <?php echo $listing['PARKINGCOVERED'] ?> </div>
				</div>
				<br />
				<div style="float:left; padding-right:10px;">Asking Price: $<?php echo number_format($listing['LISTPRICE'], 0) ?> | Status: <?php echo $listing['LISTSTATUS'] ?></div>
				<br style="clear:left" />

				<div style="padding-right:10px;"><a href="?all=true&amp;listing_id=<?php echo $listing['OID'] ?>">More Details</a></div>

				</td>
			  </tr>
			</table>
		<?

}
?>
</div>
<br \>

<div style="float:left; width:90%; border:1px solid #CCCCCC; padding-top:5px;">

<div style="font-size:18px; color:#333333">Offered By</div>
<?
//$agents = simplexml_load_file("http://realivent.com/services/get_agent_details_xml.php?username=".get_option('fl_realivent_username'));

$fields="";

$agentdata = getContentUsingCurl("http://realivent.com/services/get_agent_details_xml.php?username=".get_option('fl_realivent_username'),$fields);

$pa =& new xmlParser();
$pa->parse($agentdata);
$optp = $pa->output;
$agents = getSimpleArray($optp);
//
//		echo "<pre>";
//		print_r($agents);
//		echo "</pre>";

foreach ($agents as $agent)
{
	$agentwebsite = urldecode($agent[WEBSITE]);
	//$newagentwebsite = wordwrap($agentwebsite, 20, "<br />\n");
	$newagentwebsite = mb_substr($agentwebsite,0,25);

	?>
	<div style="padding-top:5px;">
		<div style="float:left; padding:2px;"><img style="border:1px solid black;" src="http://realivent.com/user_images/t75_<?php echo $agent[IMAGE]; ?>" alt="" /></div>
		<div style="float:left; padding-left:4px; font-size:16px;">
			<div><strong><?php echo urldecode($agent[FIRST_NAME]) ?> <?php echo urldecode($agent[LAST_NAME]) ?></strong></div>
			<div>Phone: <?php echo $agent[PHONE] ?></div>
			<div>Email: <a href='mailto:<?php echo $agent[EMAIL] ?>'><?php echo $agent[EMAIL] ?></a></div>
			<div>Website: <a href='http://<?php echo urldecode($agent[WEBSITE]) ?>'><?php echo $newagentwebsite ?></a></div>
		</div>


	<? //echo "company_logo="; echo $agent[LOGO]; echo "<br />"; ?>
	<?php if ($agent[LOGO]!='')
		{ ?>
		<div style="float:left; padding:2px;"><img style="border:0px solid black;" src="http://realivent.com/user_images/t_<?php echo $agent[LOGO]; ?>" alt="" /></div>

		<?
		}
		else
		{
			?>
			<?
		}
		?>

	</div>


	<?
}
?>

</div>

<?
}

function get_featured_listings_details($listing_id)
{

	global $sidebar_lid;
	global $sidebar_city;
	global $sidebar_state;
	global $sidebar_zip;
	global $sidebar_showzillow;
	global $sidebar_showVT;

	$sidebar_lid  = $listing_id;

	//echo "listing_id="; echo $listing_id; echo "<br>";

	$ldata = getContentUsingCurl("http://realivent.com/services/get_featured_listings_details_xml_2.php?listing_id=".$listing_id."&actives=true&pendings=true&solds=true",$fields);
	//$listing = simplexml_load_file("http://realivent.com/services/get_featured_listings_details_xml.php?listing_id=".$listing_id."");
?>
<img src="http://realivent.com/accounts/visit.php?lid=<?php echo $listing_id;?>&type=B" width="0" height="0" />
<?
$fields="";

//print_r($ldata);
$pal =& new xmlParser();
$pal->parse($ldata);
$opt = $pal->output;
$dlistings = getSimpleArray($opt);
$listing = $dlistings[0];

$sidebar_city  = urlencode($listing[CITY]);
$sidebar_state  = urlencode($listing[STATE]);
$sidebar_zip  = $listing[ZIPCODE];
$sidebar_showzillow  = $listing[DISPLAYZILLOW];
$sidebar_showVT  = $listing[VIRTUAL_TOUR_URL];

if($listing[OID] == 0)
{
?>
<table style="font-size:12px;" border='0' width="99%">

	  <tr>
		<td style="padding-left:0px;" align="left" colspan="3"><div id="listing_header" style="font-size:22px;">The Listing data for this site is no longer available.</div><div style="float:left; "></div></td>
	  </tr>
	  </table>
<?
}
else
{

	$unit = ($listing[UNIT] !='')?" ".$listing[UNIT]:"";

	if ($unit != "") $unit = ' #'.$unit;

	//print_r($listing);
	if($_GET['show']!='false')
	{
?>
<style type="text/css">
div.feature_header
{
font-size:16px;
color:#333333;
text-decoration:underline;
font-weight:bold;
}
</style>
<?
global $wpdb;
$post_name = get_query_var('name');
$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");
?>

<table style="font-size:12px;" border='0' width="99%">

	  <tr>
		<td style="padding-left:0px;" align="left" colspan="3"><div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div><div style="float:left; "></div></td>
	  </tr>
	    <tr>
			<td style="font-size:16px;">
				<?php echo urldecode($listing[TITLE]); ?>
			</td>
		</tr>
	  <tr>
		<td valign="top" align="left">
			<table style="padding-left:0px;" width="99%" border="0" cellspacing="0" cellpadding="0">
				 <tr>
					<td  valign="top">
						<!--main body-->
						<table width="99%" border="0" cellspacing="0" cellpadding="0" style="padding-left:0px; ">
							<tr>
<!--								<td style="padding-left:10px; color:white" height="20px" colspan="3" bgcolor="#333333"><a style="color:white; text-decoration:none" href='<?php echo bloginfo('url') ?>/<?php echo $fl_url ?>/?all=true'>View All Listings</a> | <a id="listing_link" target="_blank" style="color:white; text-decoration:none" href='http://www.realivent.com/print_listing.php?listing_id=<?php echo $listing[OID] ?>'>Printer Friendly Version</a> | <a id="p_listing_link" style="color:white; text-decoration:none" href='http://www.realivent.com/email_friend_cl.php?listing_id=<?php echo $listing[OID] ?>'>Email to Friend</a></td>
-->
							<td style="padding-left:10px; color:white" height="20px" colspan="3" bgcolor="#333333"><a style="color:white; text-decoration:none" href='<?php echo bloginfo('url') ?>/<?php echo $fl_url ?>/?all=true'>View All Listings</a> | <a id="listing_link" target="_blank" style="color:white; text-decoration:none" href='http://www.realivent.com/print_listing.php?listing_id=<?php echo $listing[OID] ?>'>Printer Friendly Version</a> | <a id="p_listing_link" style="color:white; text-decoration:none" href='<?php echo bloginfo('url') ?>/<?php echo $fl_url ?>/?emailfriend=true&listing_id=<?php echo $listing[OID] ?>&show=false&all=true'>Email to Friend</a><!-- | <a target="_blank" style="color:white; text-decoration:none" href='print_listing.php?listing_id=<?php //echo $oid ?>'>Save</a>--></td>

							</tr>
							<tr>
								<td width="420" valign="top" style="padding:10px;" align="left">


									<?php
									list($width_orig, $height_orig, $image_type) = getimagesize($listing[MAIN_IMAGE]);


									if($width_orig > $height_orig)
									{
										//this picture is a landscape
										$width = 400;
										$height = ($width/$width_orig)*$height_orig;
									}
									else
									{
										$height = 400;
										$width = ($height/$height_orig)*$width_orig;
									}
									?>
									<table width="99%" border="0" cellspacing="0" cellpadding="0">
									  <tr>
										<td valign="middle" height="305px" style="padding:2px;"><div align="center" id="main_image" style="border:0px solid black; padding:0px;"><img alt="" style="border:1px solid black; " src='<?php echo $listing[MAIN_IMAGE]?>' width = '<?php echo $width ?>' height='<?php echo $height ?>' /></div></td>
									  </tr>
									  <tr>
										<td width="99%" align="center">
										<script language="javascript" type="text/javascript">
										function get_image(url)
										{
											var img_html = "<img style='border:1px solid black;' src='"+url+"' alt='' />";
											window.document.getElementById('main_image').innerHTML = img_html;
										}
										</script>
										<div>
										<?
										$images = $listing[IMAGES];
										//echo sizeof($images->image);
										if(sizeof($images)>1)
										{
											foreach($images as $img)
											{
												$image = $img[content];

												?>
												<a href="javascript:get_image('<?php echo str_replace("t_", "resize_", $image) ?>')"><img width="51" alt="" height="38" style="border:1px solid black;" src="<?php echo $image ?>" /></a>
												<?

											}
										}
										?>
										</div>
										<!--<div><a target="_blank" href=http://local.live.com/default.aspx?cp=<?php //echo $row['LONGITUDE'] ?>~<?php//echo $row['LATITUDE'] ?>&lvl=1scene=3050&style=o&v=2>Bird's Eye View</a></div>-->
										</td>
									  </tr>

									</table>
								</td>


								<td width="*" valign="top" align="left" id="listing_middle_column">
								<!--main content-->
									<div id="listing_column_header"><strong>Asking Price: $<?php echo number_format($listing[PRICE], 0) ?></strong></div>
									<div>Status: <?php echo $listing[STATUS] ?></div>
									<div>Type: <?php echo $listing[TYPE] ?></div>
									<div><?php echo $listing[BEDS] ?> Beds</div>
									<div><?php echo $listing[BATHS] ?> Baths</div>
									<?php if (!number_format($listing[SQFT], 0) < 1){ ?>
									<div><?php echo number_format($listing[SQFT], 0) ?> SQFT</div>
									<?php }?>
									<?php if ($listing[STORIES] > 0){ ?>
									<div>Stories: <?php echo number_format($listing[STORIES], 0) ?></div>
									<?php }?>
									<?php if (!number_format($listing[PARKINGCOVERED], 0) < 1){ ?>
									<div>Covered Parking: <?php echo $listing[PARKINGCOVERED] ?></div>
									<?php }?>
									<?php if (number_format($listing[ASSOCFEE], 2) > 0){ ?>
									<div>HOA: $<?php echo number_format($listing[ASSOCFEE], 2) ?></div>
									<?php }?>
									<?php if ($listing[YEARBUILT] > 0){ ?>
									<div>Year Built: <?php echo $listing[YEARBUILT] ?></div>
									<?php }?>
									<?php if ($listing[STYLE] != ''){ ?>
									<div>Style: <?php echo $listing[STYLE] ?></div>
									<?php }?>
									<?php if ($listing[MLSNUM] != ''){ ?>
									<div>MLS Number: <?php echo $listing[MLSNUM] ?></div>
									<?php }?>

									<?
									$events = $listing[EVENTS];
									if(trim($events[0])!='')
									{
									?>
									<div style="padding-top:10px;">
									<HR />
									<h3>Open Houses Schedule</h3>
									<?php
									foreach($events as $event)
									{
									?>
									<!--<div style="font-size:14px;"><strong><?php //echo $event[child][6][content] ?></strong></div>-->
									<div align=left>- Date: <?php echo $event[child][1][content] ?></div>
									<div align=left style="padding-left:10px;">From: <?php echo $event[child][2][content] ?> - <?php echo $event[child][3][content] ?></div>
									</div>
									<hr>
									<?php
									}
									}
									?>

									<?php if ($listing[IVR] != ''){ ?>
									<div style="padding-top:10px;">
									<HR />
									<h3>24 HR Recorded Information</h3>
									<div style="font-size:10px;">Call anytime to get more information about this property</div>
									<div align=left style=" padding-left:0px;font-size:16px;"><strong><?php echo $listing[IVR] ?></strong></div>
									</div>
									<hr>
									<?php
									}
									?>

									<div style="padding-top:10px;">

									<?php
									$agent = convertIndexToKey($listing[AGENT]);
									$agentwebsite = urldecode($agent[WEBSITE]);

									//$newagentwebsite = wordwrap($agentwebsite, 20, "<br />\n");
									$newagentwebsite = mb_substr($agentwebsite,0,25);


									$website = (urldecode($agent[WEBSITE])!='')?'Website: <a href="http://'.urldecode($agent[WEBSITE]).'">'.$newagentwebsite.'</a>':'';

									?>
									<!--<div><a href=http://www.realivent.com/user_profile.php?id=<?php //echo $arow['ID'] ?>>view profile</a> | <a href=http://www.realivent.com/user_listings.php?id=<?php //echo $arow['ID'] ?>>view listings</a> | <a href=http://www.realivent.com/user_stories.php?id=<?php //echo $arow['ID'] ?>>view news</a> | <a href=http://www.realivent.com/user_profile.php?id=<?php //echo $arow['ID'] ?>>view blog</a></div>-->
											<div style="border:1px solid #999999; padding:4px; text-align:center">
											<h3>Offered By</h3>
											<?php
											if($agent[IMAGE]!='http://realivent.com/user_images/t75_')
											{
											?>
											<div style="padding:2px;"><img style="border:1px solid black;" src='<?php echo $agent[IMAGE] ?>' alt="" /></div>
											<div style="width:90% padding-left:0px; padding-top:10px;">
												<div><strong><?php echo urldecode($agent[FIRST_NAME]) ?> <?php echo urldecode($agent[LAST_NAME]) ?></strong></div>
												<div>Phone: <?php echo $agent[PHONE] ?></div>
											</div>
											<div style="clear:both; text-align:center">
											<div style="padding-bottom:5px;">Email: <a href='mailto:<?php echo $agent[EMAIL] ?>'><?php echo $agent[EMAIL] ?></a></div>
											<div style="padding-bottom:5px;">
											<?php echo $website ?>
											</div>

											<?php if ($agent[LOGO]!='')
												{ ?>
												<img style="border:0px solid black;" src="<?php echo $agent[LOGO]; ?>" alt="" />

												<?
												}
												else
												{
													?>
													<?
												}
												?>
												</div>

											<?php
											}
											else
											{
											?>
											<div style="float:left; width:90% padding-left:0px; padding-top:10px;">
												<div><strong><?php echo urldecode($agent[FIRST_NAME]) ?> <?php echo urldecode($agent[LAST_NAME]) ?></strong></div>
												<div>Phone: <?php echo $agent[PHONE] ?></div>
											</div>
											<div style="clear:both; text-align:left">
											<div style="padding-bottom:5px;">Email: <a href='mailto:<?php echo $agent[EMAIL] ?>'><?php echo $agent[EMAIL] ?></a></div>
											<div style="padding-bottom:5px;">
											<?php echo $website ?>
											</div>

											<?php if ($agent[LOGO]!='')
												{ ?>
												<img style="border:0px solid black;" src="<?php echo $agent[LOGO]; ?>" alt="" />

												<?
												}
												else
												{
													?>
													<?
												}
												?>
												</div>


											<?
											}
											?>

											</div>


									</div>

								</td>
							</tr>
						</table>
				</td>
			</tr>

			<tr>
			<td colspan="2" width="99%">

			<h3>Description</h3>
			<div style="padding-right:10px; "><?php echo stripslashes($listing[REMARKS]) ?></div><br />

			</td>
			</tr>

			<tr>
				<td colspan="2" width="99%">


					<?php
					$features = $listing[FEATURES];
					$kitchen = $features[0][child];
					$interior = $features[1][child];
					$exterior = $features[2][child];

					?>
					<div style="padding-left:0px; padding-top:10px; text-align:left">
					<div style="padding-bottom:0px;"><h3>Kitchen Features</h3></div>
					<?
					$i=0;
					if($kitchen) {
						foreach($kitchen as $itm)
						{
							$item = $itm[content];
							echo "<div style='float:left; padding-left:5px; width:120px;'>- ".$item."</div>";
							$i++;
						}}
					?>

					<div style="clear:left; padding-top:10px;"><h3>Interior Features</h3></div>
					<?
					$i=0;
					if($interior) {
						foreach($interior as $itm)
						{
							$item = $itm[content];
							echo "<div style='float:left; padding-left:5px; width:120px;'>- ".$item."</div>";
							$i++;
						} }
					?>

					<div style="clear:left; padding-top:10px;"><h3>Exterior Features</h3></div>
					<?
					$i=0;
					if($exterior) {
						foreach($exterior as $itm)
						{
							$item = $itm[content];
							echo "<div style='float:left; padding-left:5px; width:120px;'>- ".$item."</div>";
							$i++;
						} }
					?>
					</div>



				</td>
			</tr>

		</table>
	</td>
	</tr>
</table>

<?
	}

	if(isset($_GET['map']))
	{
	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>

		<iframe align="middle" frameborder="0" scrolling="no" style="width: 99%; height: 620px; border:0px solid #0066CC;" src='http://realivent.com/featuredlistings_map_frame.php?lat=<?php echo $listing[LATITUDE] ?>&lng=<?php echo $listing[LONGITUDE] ?>&username=<?php echo get_option('fl_realivent_username') ?>'></iframe>


	<?
	}

	if(isset($_GET['yelp_reviews']))
	{

		$yelp_address = $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE];
	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>

		<iframe align="middle" frameborder="0" scrolling="no" style="width: 99%; height: 1500px; border:0px solid #0066CC;" src='http://realivent.com/featuredlistings_yelp_frame.php?lat=<?php echo $listing[LATITUDE] ?>&lng=<?php echo $listing[LONGITUDE] ?>&username=<?php echo get_option('fl_realivent_username') ?>&yelp_address=<?php echo urlencode($yelp_address) ?>&main_image=<? echo $listing[MAIN_T_IMAGE] ?>&city=<?php echo urlencode($listing[CITY]) ?>&state=<?php echo urlencode($listing[STATE]) ?>&zip=<?php echo urlencode($listing[ZIPCODE]) ?>'></iframe>


	<?
	}

	if(isset($_GET['zillow_comps']))
	{

		$prop_address = $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE];
	?>
<!--	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
-->
		<iframe align="middle" frameborder="0" scrolling="no" style="width: 99%; height: 1500px; border:0px solid #0066CC;" src='http://realivent.com/thisprop_zillow_map_frame.php?city=<?php echo $listing[CITY] ?>&state=<?php echo $listing[STATE] ?>&zillowkey=<?php echo get_option('zillow_api') ?>&prop_address=<?php echo urlencode($prop_address) ?>&zip=<? echo $listing[ZIPCODE] ?>'></iframe>


	<?
	}

	if(isset($_GET['neighborhood']))
	{
	?>

		<iframe align="left" frameborder="0" scrolling="no" style="width: 99%; height:2150px; border:0px solid #0066CC;" src='http://realivent.com/api/neighborhood_frame.php?listing_id=<?php echo $listing[OID] ?>'></iframe>


	<?
	}

	if(isset($_GET['emailfriend']))
	{
	?>

		<iframe align="left" frameborder="0" scrolling="no" style="width: 99%; height:2150px; border:0px solid #0066CC;" src='http://realivent.com/email_friend_cl_frame.php?listing_id=<?php echo $listing[OID] ?>'></iframe>


	<?
	}

	if(isset($_GET['more_info']))
	{
		if(!$_POST['submit_more_info'])
		{
	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
	<form action="" name="theform" method=post style="padding-left:40px;">
		<h2>Request for more information about this property</h2>
		<table width="99%" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF" border="0">
			<tr>
				<td>Name:<br /><input style="width:50%" maxlength="50" name="ContactName" value=""></td>
			</tr>
			<tr>

				<td>Email Address:<br /><input style="width:50%" maxlength="50" name="Email" value=""></td>
			</tr>

			<tr>

				<td>Additional Information Requested<br /><textarea style="width:50%" name="Message" rows="3" wrap="physical" cols="30"></textarea></td>
			</tr>
			<tr>

				<td>Telephone:<br /><input style="width:50%" maxlength="30" name="Phone" value=""></td>
			</tr>
			<tr>
				<td>Address:<br /><input style="width:50%" maxlength="50" name="Address" value=""></td>
			</tr>
			<tr>

				<td>City:<br /><input style="width:50%" maxlength="50" name="City"value=""></td>
			</tr>
			<tr>
				<td width='50%' align=left><input style="width:200px" type="submit" value="Send Email" name="submit_more_info"></td>
			</tr>

		</table>
	</form>
	<?
		}
		else
		{
			// To send HTML mail, the Content-type header must be set
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

			// Additional headers
			$headers .= 'From:'.$_POST['ContactName']."<".$_POST['Email']."> \r\n";

			$message = '<B>Request for more information: </b>'.$listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE]."<br />";
			$message .= '<br /><strong>Full Name: </strong> ' . $_POST['ContactName'];
			$message .= '<br /><strong>Email: </strong> ' . $_POST['Email'];
			$message .= '<br /><strong>Phone: </strong> ' . $_POST['Phone'];
			$message .= '<br /><strong>Address: </strong> ' . $_POST['Address'];
			$message .= '<br /><strong>City: </strong> ' .$_POST['City'];
			$message .= '<br /><strong>Comments: </strong><br />' . $_POST['Message'];

			$agent = convertIndexToKey($listing[AGENT]);

			$to = $agent[EMAIL];
			$subject = 'New Request for more information';
			$body = $message;
			mail($to, $subject, $body, $headers);


	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
	<h2>Thank you for requesting more information, I will respond to your questions, as soon as I can.</h2>
	<?
		}
	}

	if(isset($_GET['showing']))
	{
		if(!$_POST['submit_showing'])
		{
	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
	<form action="" name="theform" method=post style="padding-left:40px;">
		<h2>Request for more information about this property</h2>
		<table width="99%" cellpadding="0" cellspacing="2" bgcolor="#FFFFFF" border="0">
			<tr>
				<td>Name:<br /><input style="width:50%" maxlength="50" name="ContactName" value=""></td>
			</tr>
			<tr>

				<td>Email Address:<br /><input style="width:50%" maxlength="50" name="Email" value=""></td>
			</tr>
			<tr>

				<td>Telephone:<br /><input style="width:50%" maxlength="30" name="Phone" value=""></td>
			</tr>

			<tr>

				<td>Please give details about when you would like to view the property<br /><textarea style="width:50%" name="Message" rows="3" wrap="physical" cols="30"></textarea></td>
			</tr>
			<tr>
				<td width='50%' align=left><input style="width:200px" type="submit" value="Send Email" name="submit_showing"></td>
			</tr>

		</table>
	</form>

	<?
		}
		else
		{
			// To send HTML mail, the Content-type header must be set
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

			// Additional headers
			$headers .= 'From:'.$_POST['ContactName']."<".$_POST['Email']."> \r\n";

			$message = '<B>Request a Showing: </b>'.$listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE]."<br />";
			$message .= '<br /><strong>Full Name: </strong> ' . $_POST['ContactName'];
			$message .= '<br /><strong>Email: </strong> ' . $_POST['Email'];
			$message .= '<br /><strong>Phone: </strong> ' . $_POST['Phone'];
			$message .= '<br /><strong>Showing Details: </strong><br />' . $_POST['Message'];

			$agent = convertIndexToKey($listing[AGENT]);

			$to = $agent[EMAIL];
			$subject = 'Request for Showing';
			$body = $message;
			mail($to, $subject, $body, $headers);


	?>
	<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
	<h2>Thank you for requesting more information, I will respond to your questions, as soon as I can.</h2>
	<?
		}
	}

	if(isset($_GET['calculator']))
	{
		//if(!isset($_POST['submit']))
		/*
		PHP Mortgage Calculator
		version: 1.1
		last update: Jan 1, 2003
		----------------------------------------------------
		The PHP Mortgage Calculator tries to figure out a home
		owners mortgage payments, and the breakdown of each monthly
		payment.

		The calculator accepts:
		Price (cost of home in US Dollars)
		Percentage of Down Payment
		Length of Mortgage
		Annual Interest Rate

		Based on the four items that the user enters, we can figure
		out the down payment (in US Dollars), the ammount that the
		buyer needs to finance, and the monthly finance payment.
		The calculator can also break down the monthly payments
		so we know how much goes towards the mortgage's interest,
		the mortgage's principal, the loan's Private Mortgage Insurance
		(if less that 20% was used as a down payment), and an rough
		estimate of the property's residential tax

		[ See below for LICENSE ]
		*/

		/* --------------------------------------------------- *
		* Set Form DEFAULT values
		* --------------------------------------------------- */
		$default_sale_price              = $listing[PRICE];
		$default_annual_interest_percent = 7.0;
		$default_year_term               = 30;
		$default_down_percent            = 10;
		$default_show_progress           = TRUE;
		/* --------------------------------------------------- */



		/* --------------------------------------------------- *
		* Initialize Variables
		* --------------------------------------------------- */
		$sale_price                      = 0;
		$annual_interest_percent         = 0;
		$year_term                       = 0;
		$down_percent                    = 0;
		$this_year_interest_paid         = 0;
		$this_year_principal_paid        = 0;
		$form_complete                   = false;
		$show_progress                   = false;
		$monthly_payment                 = false;
		$show_progress                   = false;
		$error                           = false;
		/* --------------------------------------------------- */


		/* --------------------------------------------------- *
		* Set the USER INPUT values
		* --------------------------------------------------- */
		if (isset($_REQUEST['form_complete'])) {
			$sale_price                      = $_REQUEST['sale_price'];
			$annual_interest_percent         = $_REQUEST['annual_interest_percent'];
			$year_term                       = $_REQUEST['year_term'];
			$down_percent                    = $_REQUEST['down_percent'];
			$show_progress                   = (isset($_REQUEST['show_progress'])) ? $_REQUEST['show_progress'] : false;
			$form_complete                   = $_REQUEST['form_complete'];
		}
		/* --------------------------------------------------- */


		// If HTML headers have not already been sent, we'll print some here
		if (!headers_sent()) {
			print("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'><HTML>");
			print("<head><title>Mortgage Calculator</title></HEAD><BODY>");
			print("<body bgcolor='#33ccff'>");
			print("<H1 style='margin-bottom: 35px;'>PHP Mortgage Calculator</h1>");
			print("<hr>\n\n");
			$print_footer = TRUE;
		} else {
			$print_footer = FALSE;
		}

		// Style Sheet
    ?>
    <style type="text/css">
        <!--
            td {
                font-size : 11px;
                font-family : tahoma, helvetica, arial, lucidia, sans-serif;
                color : #000000;
            }
        -->
    </style>


    <?php
    /* --------------------------------------------------- */
    // This function does the actual mortgage calculations
    // by plotting a PVIFA (Present Value Interest Factor of Annuity)
    // table...
    function get_interest_factor($year_term, $monthly_interest_rate) {
    	global $base_rate;

    	$factor      = 0;
    	$base_rate   = 1 + $monthly_interest_rate;
    	$denominator = $base_rate;
    	for ($i=0; $i < ($year_term * 12); $i++) {
    		$factor += (1 / $denominator);
    		$denominator *= $base_rate;
    	}
    	return $factor;
    }
    /* --------------------------------------------------- */

    // If the form is complete, we'll start the math
    if ($form_complete) {
    	// We'll set all the numeric values to JUST
    	// numbers - this will delete any dollars signs,
    	// commas, spaces, and letters, without invalidating
    	// the value of the number
    	$sale_price              = ereg_replace( "[^0-9.]", "", $sale_price);
    	$annual_interest_percent = eregi_replace("[^0-9.]", "", $annual_interest_percent);
    	$year_term               = eregi_replace("[^0-9.]", "", $year_term);
    	$down_percent            = eregi_replace("[^0-9.]", "", $down_percent);

    	if (((float) $year_term <= 0) || ((float) $sale_price <= 0) || ((float) $annual_interest_percent <= 0)) {
    		$error = "You must enter a <b>Sale Price of Home</b>, <b>Length of Motgage</b> <i>and</i> <b>Annual Interest Rate</b>";
    	}

    	if (!$error) {
    		$month_term              = $year_term * 12;
    		$down_payment            = $sale_price * ($down_percent / 100);
    		$annual_interest_rate    = $annual_interest_percent / 100;
    		$monthly_interest_rate   = $annual_interest_rate / 12;
    		$financing_price         = $sale_price - $down_payment;
    		$monthly_factor          = get_interest_factor($year_term, $monthly_interest_rate);
    		$monthly_payment         = $financing_price / $monthly_factor;
    	}
    } else {
    	if (!$sale_price)              { $sale_price              = $default_sale_price;              }
    	if (!$annual_interest_percent) { $annual_interest_percent = $default_annual_interest_percent; }
    	if (!$year_term)               { $year_term               = $default_year_term;               }
    	if (!$down_percent)            { $down_percent            = $default_down_percent;            }
    	if (!$show_progress)           { $show_progress           = $default_show_progress;           }
    }

    if ($error) {
    	print("<font color=\"red\">" . $error . "</font><br /><br />\n");
    	$form_complete   = false;
    }

    global $wpdb;
    $post_name = get_query_var('name');
    $fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");
?>
<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
<font size="-1" color="#000000">This can be used to figure out monthly payments of a home mortgage loan, based on the home's sale price, the term of the loan desired, buyer's down payment percentage, and the loan's interest rate. This calculator factors in PMI (Private Mortgage Insurance) for loans where less than 20% is put as a down payment. Also taken into consideration are the town property taxes, and their effect on the total monthly mortgage payment.<br /></font>

<form method="GET" name="information" action="httP://<?php echo $_SERVER['HTTP_HOST'] ?>/<?php echo $post_name ?>/">
<input type="hidden" name="form_complete" value="1">
<input type="hidden" name="show" value="false">
<input type="hidden" name="calculator" value="true">
<input type="hidden" name="all" value="true">
<input type="hidden" name="listing_id" value="<?php echo $listing[OID] ?>">
<table cellpadding="2" cellspacing="0" border="0" width="99%">
    <tr valign="top">
        <td align="right"><img src="/images/clear.gif" width="225" height="1" border="0" alt="" /></td>
        <td align="smalltext" width="99%"><img src="/images/clear.gif" width="250" height="1" border="0" alt="" /></td>
    </tr>
    <tr valign="top" bgcolor="#cccccc">
        <td align="center" colspan="2"><b>Purchase &amp; Financing Information</b></td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td align="right" nowrap="nowrap">Sale Price of Home:</td>
        <td width="99%" align="left">$<input type="text" size="10" name="sale_price" value="<?php echo $sale_price; ?>">(In Dollars)</td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td align="right" nowrap="nowrap">Percentage Down:</td>
        <td align="left"><input type="text" size="5" name="down_percent" value="<?php echo $down_percent; ?>">%</td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td align="right" nowrap="nowrap">Length of Mortgage:</td>
        <td align="left"><input type="text" size="3" name="year_term" value="<?php echo $year_term; ?>">years</td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td align="right" nowrap="nowrap">Annual Interest Rate:</td>
        <td align="left"><input type="text" size="5" name="annual_interest_percent" value="<?php echo $annual_interest_percent; ?>">%</td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td align="right" nowrap="nowrap">Explain Calculations:</td>
        <td align="left"><input type="checkbox" name="show_progress" value="1" <?php if ($show_progress) { print("checked"); } ?>> Show me the calculations and amortization</td>
    </tr>
    <tr valign="top" bgcolor="#eeeeee">
        <td>&nbsp;</td>
        <td align="left"><input type="submit" value="Calculate"><br /><?php if ($form_complete) { print("<a href=\"" . $_SERVER['PHP_SELF'] . "\">Start Over</a><br />"); } ?><br /></td>
    </tr>
<?php
// If the form has already been calculated, the $down_payment
// and $monthly_payment variables will be figured out, so we
// can show them in this table
if ($form_complete && $monthly_payment) {
?>
        <tr valign="top">
            <td align="center" colspan="2" bgcolor="#000000"><font color="#ffffff"><b>Mortgage Payment Information</b></font></td>
        </tr>
        <tr valign="top" bgcolor="#eeeeee">
            <td align="right">Down Payment:</td>
            <td><b><?php echo "\$" . number_format($down_payment, "2", ".", ","); ?></b></td>
        </tr>
        <tr valign="top" bgcolor="#eeeeee">
            <td align="right">Amount Financed:</td>
            <td><b><?php echo "\$" . number_format($financing_price, "2", ".", ","); ?></b></td>
        </tr>
        <tr valign="top" bgcolor="#cccccc">
            <td align="right">Monthly Payment:</td>
            <td><b><?php echo "\$" . number_format($monthly_payment, "2", ".", ","); ?></b><br /><font>(Principal &amp; Interest ONLY)</font></td>
        </tr>
        <?php
        if ($down_percent < 20) {
        	$pmi_per_month = 55 * ($financing_price / 100000);
        ?>
                <tr valign="top" bgcolor="#FFFFCC">
                    <td align="right">&nbsp;</td>
                    <td>
                        <br />
                        Since you are putting LESS than 20% down, you will need to pay PMI (<a href="http://www.google.com/search?hl=en&q=private+mortgage+insurance">Private Mortgage Insurance</a>), which tends to be about $55 per month for every $100,000 financed (until you have paid off 20% of your loan). This could add <?php echo "\$" . number_format($pmi_per_month, "2", ".", ","); ?> to your monthly payment.
                    </td>
                </tr>
                <tr valign="top" bgcolor="#FFFF99">
                    <td align="right">Monthly Payment:</td>
                    <td><b><?php echo "\$" . number_format(($monthly_payment + $pmi_per_month), "2", ".", ","); ?></b><br /><font>(Principal &amp; Interest, and PMI)</td>
                </tr>
        <?php
        }
        ?>
        <tr valign="top" bgcolor="#CCCCFF">
            <td align="right">&nbsp;</td>
            <td>
                <br />
                <?php
                $assessed_price          = ($sale_price * .85);
                $residential_yearly_tax  = ($assessed_price / 1000) * 14;
                $residential_monthly_tax = $residential_yearly_tax / 12;

                if ($pmi_per_month) {
                	$pmi_text = "PMI and ";
                }
                ?>
                Residential (or Property) Taxes are a little harder to figure out... In Massachusetts, the average resedential tax rate seems to be around $14 per year for every $1,000 of your property's assessed value.
                <br /><br />
                Let's say that your property's <i>assessed value</i> is 85% of what you actually paid for it - <?php echo "\$" . number_format($assessed_price, "2", ".", ","); ?>. This would mean that your yearly residential taxes will be around <?php echo "\$" . number_format($residential_yearly_tax, "2", ".", ","); ?>
                This could add <?php echo "\$" . number_format($residential_monthly_tax, "2", ".", ","); ?> to your monthly payment.
            </td>
        </tr>
        <tr valign="top" bgcolor="#9999FF">
            <td align="right">TOTAL Monthly Payment:</td>
            <td><b><?php echo "\$" . number_format(($monthly_payment + $pmi_per_month + $residential_monthly_tax), "2", ".", ","); ?></b><br /><font>(including <?php echo $pmi_text; ?> residential tax)</font></td>
        </tr>
<?php
}
?>
</table>
</form>
<?php
// This prints the calculation progress and
// the instructions of HOW everything is figured
// out
if ($form_complete && $show_progress) {
	$step = 1;
?>
        <br /><br />
        <table cellpadding="5" cellspacing="0" border="1" width="99%">
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    The <b>down payment</b> = The price of the home multiplied by the percentage down divided by 100 (for 5% down becomes 5/100 or 0.05)<br /><br />
                    $<?php echo number_format($down_payment,"2",".",","); ?> = $<?php echo number_format($sale_price,"2",".",","); ?> X (<?php echo $down_percent; ?> / 100)
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    The <b>interest rate</b> = The annual interest percentage divided by 100<br /><br />
                    <?php echo $annual_interest_rate; ?> = <?php echo $annual_interest_percent; ?>% / 100
                </td>
            </tr>
            <tr valign="top" bgcolor="#cccccc">
                <td colspan="2">
                    The <b>monthly factor</b> = The result of the following formula:
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    The <b>monthly interest rate</b> = The annual interest rate divided by 12 (for the 12 months in a year)<br /><br />
                    <?php echo $monthly_interest_rate; ?> = <?php echo $annual_interest_rate; ?> / 12
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    The <b>month term</b> of the loan in months = The number of years you've taken the loan out for times 12<br /><br />
                    <?php echo $month_term; ?> Months = <?php echo $year_term; ?> Years X 12
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    The montly payment is figured out using the following formula:<br />
                    Monthly Payment = <?php echo number_format($financing_price, "2", "", ""); ?> * (<?php echo number_format($monthly_interest_rate, "4", "", ""); ?> / (1 - ((1 + <?php echo number_format($monthly_interest_rate, "4", "", ""); ?>)<sup>-(<?php echo $month_term; ?>)</sup>)))
                    <br /><br />
                    The <a href="#amortization">amortization</a> breaks down how much of your monthly payment goes towards the bank's interest, and how much goes into paying off the principal of your loan.
                </td>
            </tr>
        </table>
        <br />
<?php
// Set some base variables
$principal     = $financing_price;
$current_month = 1;
$current_year  = 1;
// This basically, re-figures out the monthly payment, again.
$power = -($month_term);
$denom = pow((1 + $monthly_interest_rate), $power);
$monthly_payment = $principal * ($monthly_interest_rate / (1 - $denom));

//if we want to show all months - this can get very long
if($_GET['show_progress'])
{

	print("<br /><br /><a name=\"amortization\"></a>Amortization For Monthly Payment: <b>\$" . number_format($monthly_payment, "2", ".", ",") . "</b> over " . $year_term . " years<br />\n");
	print("<table cellpadding=\"5\" cellspacing=\"0\" bgcolor=\"#eeeeee\" border=\"1\" width=\"99%\">\n");


	// This LEGEND will get reprinted every 12 months
	$legend  = "\t<tr valign=\"top\" bgcolor=\"#cccccc\">\n";
	$legend .= "\t\t<td align=\"right\"><b>Month</b></td>\n";
	$legend .= "\t\t<td align=\"right\"><b>Interest Paid</b></td>\n";
	$legend .= "\t\t<td align=\"right\"><b>Principal Paid</b></td>\n";
	$legend .= "\t\t<td align=\"right\"><b>Remaing Balance</b></td>\n";
	$legend .= "\t</tr>\n";

	echo $legend;

	// Loop through and get the current month's payments for
	// the length of the loan

	while ($current_month <= $month_term) {
		$interest_paid     = $principal * $monthly_interest_rate;
		$principal_paid    = $monthly_payment - $interest_paid;
		$remaining_balance = $principal - $principal_paid;

		$this_year_interest_paid  = $this_year_interest_paid + $interest_paid;
		$this_year_principal_paid = $this_year_principal_paid + $principal_paid;

		print("\t<tr valign=\"top\" bgcolor=\"#eeeeee\">\n");
		print("\t\t<td align=\"right\">" . $current_month . "</td>\n");
		print("\t\t<td align=\"right\">\$" . number_format($interest_paid, "2", ".", ",") . "</td>\n");
		print("\t\t<td align=\"right\">\$" . number_format($principal_paid, "2", ".", ",") . "</td>\n");
		print("\t\t<td align=\"right\">\$" . number_format($remaining_balance, "2", ".", ",") . "</td>\n");
		print("\t</tr>\n");

		($current_month % 12) ? $show_legend = FALSE : $show_legend = TRUE;

		if ($show_legend) {
			print("\t<tr valign=\"top\" bgcolor=\"#ffffcc\">\n");
			print("\t\t<td colspan=\"4\"><b>Totals for year " . $current_year . "</td>\n");
			print("\t</tr>\n");

			$total_spent_this_year = $this_year_interest_paid + $this_year_principal_paid;
			print("\t<tr valign=\"top\" bgcolor=\"#ffffcc\">\n");
			print("\t\t<td>&nbsp;</td>\n");
			print("\t\t<td colspan=\"3\">\n");
			print("\t\t\tYou will spend \$" . number_format($total_spent_this_year, "2", ".", ",") . " on your house in year " . $current_year . "<br />\n");
			print("\t\t\t\$" . number_format($this_year_interest_paid, "2", ".", ",") . " will go towards INTEREST<br />\n");
			print("\t\t\t\$" . number_format($this_year_principal_paid, "2", ".", ",") . " will go towards PRINCIPAL<br />\n");
			print("\t\t</td>\n");
			print("\t</tr>\n");

			print("\t<tr valign=\"top\" bgcolor=\"#ffffff\">\n");
			print("\t\t<td colspan=\"4\">&nbsp;<br /><br /></td>\n");
			print("\t</tr>\n");

			$current_year++;
			$this_year_interest_paid  = 0;
			$this_year_principal_paid = 0;

			if (($current_month + 6) < $month_term) {
				echo $legend;
			}
		}

		$principal = $remaining_balance;
		$current_month++;
	}
}
print("</table>\n");

}

	}

	if(isset($_GET['qr_code']))
	{

?>
<h2>QR Code Generator</h2>
<table cellpadding="5" cellspacing="5" id="data_grid">
   	<tr>
   		<td>
   		<table cellpadding="5" cellspacing="5">
   			<tr>
	       		<td style="border:0px">URL</td>
	       		<td style="border:0px"><input type="text" name="qr_url" id="qr_url" value="http://realivent.com/vt/<?php echo $_REQUEST['listing_id'];?>"></td>
	       	</tr>
	       	<tr>
	       		<td style="border:0px">Select Size</td>
	       		<td style="border:0px">
	       			<select name="qr_size" id="qr_size">
	       				<option value="50x50">50x50</option>
	       				<option value="75x75">75x75</option>
	       				<option value="100x100">100x100</option>
	       				<option value="125x125">125x125</option>
	       				<option value="150x150">150x150</option>
	       				<option value="175x175">175x175</option>
	       				<option value="200x200">200x200</option>
	       				<option value="300x300">300x300</option>
	       				<option value="400x400">400x400</option>
	       				<option value="500x500">500x500</option>
	       				<option value="1000x1000">1000x1000</option>
	       			</select>
	       		</td>
	       	</tr>
	       	<tr>
	       		<td style="border:0px">
	       			<a href="javascript:;" onclick="previewQR('<?php echo $_REQUEST['listing_id'];?>')">Preview</a>
	       		</td>
	       		<td style="border:0px">
	       			<a href="javascript:;" onclick="downloadQR('<?php echo $_REQUEST['listing_id'];?>')">Download</a>
	       		</td>
	       	</tr>
	    </table>
   		</td>
   		<td align="center" id="preview_qr" width="210" height="210" bgcolor="#EEEEEE">
   			PREVIEW
   		</td>
   	</tr>
   </table>
<script>
function previewQR(id) {
	qr_size = document.getElementById("qr_size").value;
	qr_url = document.getElementById("qr_url").value;
	document.getElementById("preview_qr").innerHTML = "<img src='https://chart.googleapis.com/chart?chs="+qr_size+"&cht=qr&chl="+qr_url+"'>";
}

function downloadQR(id) {
	qr_size = document.getElementById("qr_size").value;
	qr_url = document.getElementById("qr_url").value;
	window.location='http://realivent.com/poster/account/download_qr.php?qr_size='+qr_size+'&qr_url='+encodeURIComponent(qr_url);
}
</script>

<?
	}

	if(isset($_GET['street_view']))
	{

?>
<h2>Street View</h2>
<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA"
            type="text/javascript"></script>
    <script type="text/javascript">

    var myPano;
    function initialize() {
    	var fenwayPark = new GLatLng(<?php echo $listing[LATITUDE] ?>,<?php echo $listing[LONGITUDE] ?>);
    	panoramaOptions = { latlng:fenwayPark };
    	myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
    	GEvent.addListener(myPano, "error", handleNoFlash);
    }

    function handleNoFlash(errorCode) {
    	if (errorCode == FLASH_UNAVAILABLE) {
    		alert("Error: Flash doesn't appear to be supported by your browser");
    		return;
    	}
    }
    </script>
  </head>

  <body onload="initialize()" onunload="GUnload()">
    <div name="pano" id="pano" style="width: 500px; height: 300px"></div>
  </body>

<?
	}

	if(isset($_GET['birdseye']))
	{

?>
<h2>Birds-Eye View</h2>

<div id="listing_header" style="font-size:24px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>

<iframe align="middle" frameborder="0" scrolling="no" style="width: 99%; height: 500px; border:0px solid #0066CC;" src='http://realivent.com/birdseyeview_map_frame.php?lat=<?php echo $listing[LATITUDE] ?>&lng=<?php echo $listing[LONGITUDE] ?>'></iframe>


<?
	}

	if(isset($_GET['areaschools']))
	{

?>
<h2>Area Schools Near: <?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></h2>

<!--<div id="listing_header" style="font-size:18px;"><?php echo $listing[STREETNUM]." ".$listing[STREETDIR]." ".$listing[STREETNAME]." ".$listing[STREETSUFFIX].$unit.", ".$listing[CITY]." ".$listing[STATE] ?></div>
-->

<iframe align="left" frameborder="0" scrolling="no" style="width: 99%; height:1300px; border:0px solid #0066CC;" src='http://nces.ed.gov/globallocator/index.asp?search=1&State=<?php echo $listing[STATE] ?>&city=<?php echo $listing[CITY] ?>&zipcode=<?php echo $listing[ZIPCODE] ?>&miles=&itemname=&soryby=city&School=1&PrivSchool=1&College=1&Library=1&Status=Search+Finished&Records=0'></iframe>


<?
	}
?>

<?
if (!function_exists('dynamic_sidebar') && !dynamic_sidebar(1) )
//if(1)
//if ( !function_exists('dynamic_sidebar') && !dynamic_sidebar('Sidebar_1') )
{
	echo "<div style='width:98%; padding-top:20px; padding-left:10px; clear:both'>\n";
	echo "<h2>Quick Links";
	echo "</h2>\n";

	global $wpdb;
	$post_name = get_query_var('name');
	$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");

	echo "<table cellpadding='5px' cellspacing='5px' width='99%' border='0' bgcolor='#FFFFFF' style='border:1px solid #999999; font-size:12px;'>\n";
	echo "<tr>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='28%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\" align\"right\">Neighborhood Information</a></td>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/reviews_sm.png\" border=\"0\" /></a></td><td width='28%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\">Points of Interest and Reviews</a></td>\n";
	echo "</td>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/comps_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;zillow_comps=true&amp;show=false&amp;all=true\">Comparables and Price Trends</a></td>\n";
	echo "</td>\n";
	echo "</tr>\n";

	echo "<tr>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds2_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;map=true&amp;show=false&amp;all=true\">View Map</a></td>\n";
	echo "</td>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;birdseye=true&amp;show=false&amp;all=true\">Bird's Eye View</a></td>\n";
	echo "</td>\n";
	//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a target='_blank' href=\"http://nces.ed.gov/globallocator/index.asp?search=1&State=$sidebar_state&city=$sidebar_city&zipcode=sidebar_zip&miles=&itemname=&soryby=city&School=1&PrivSchool=1&College=1&Library=1&Status=Search+Finished&Records=0\">Area Schools</a></td>\n";

	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;areaschools=true&amp;show=false&amp;all=true\">Area Schools</a></td>\n";

	echo "</td>\n";
	echo "</tr>\n";

	echo "<tr>\n";
	//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='28%'><a target='_blank' href=\"http://www.realivent.com/email_friend_cl.php?listing_id=$sidebar_lid\">Email to Friend</a></td>";

	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;emailfriend=true&amp;show=false&amp;all=true\">Email to Friend</a></td>\n";

	echo "</td>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;more_info=true&amp;show=false&amp;all=true\">Request More Information</a>\n";
	echo "</td>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/requestinfo_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;showing=true&amp;show=false&amp;all=true\">Schedule a Showing</a></td>\n";
	echo "</td>\n";
	echo "</tr>\n";

	echo "<tr>\n";
	echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/calculator_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;calculator=true&amp;show=false&amp;all=true\">Calculate Payment</a></td>\n";
	echo "</td>\n";
	echo "</tr>\n";

	echo "<tr>\n";
	echo "<td width='5%' align='left'><a href=\"http://realivent.com/poster/account/download_pdf.php?listing_id=$sidebar_lid\"><img src=\"http://www.realivent.com/graphics/flwidget/pdf-icon.png\" border=\"0\" /></a></td><td width='28%'><a href=\"http://realivent.com/poster/account/download_pdf.php?listing_id=$sidebar_lid\">Print PDF</a></td>\n";
	echo "</td>\n";
	echo "</tr>\n";




	echo "</table>\n";

	echo "</div>\n";
}
?>

<?
}
}

function get_featured_listings_id($listing_id)
{

	global $sidebar_lid;
	global $sidebar_city;
	global $sidebar_state;
	global $sidebar_zip;
	global $sidebar_showzillow;
	global $sidebar_showVT;

	$sidebar_lid  = $listing_id;

	//echo "listing_id="; echo $listing_id; echo "<br>";

	$ldata = getContentUsingCurl("http://realivent.com/services/get_featured_listings_details_xml_2.php?listing_id=".$listing_id."&actives=true&pendings=true&solds=true",$fields);
	//$listing = simplexml_load_file("http://realivent.com/services/get_featured_listings_details_xml.php?listing_id=".$listing_id."");

	$fields="";

	//print_r($ldata);
	$pal =& new xmlParser();
	$pal->parse($ldata);
	$opt = $pal->output;
	$dlistings = getSimpleArray($opt);
	$listing = $dlistings[0];

	$sidebar_city  = urlencode($listing[CITY]);
	$sidebar_state  = urlencode($listing[STATE]);
	$sidebar_zip  = $listing[ZIPCODE];
	$sidebar_showzillow = $listing[DISPLAYZILLOW];
	$sidebar_showVT  = $listing[VIRTUAL_TOUR_URL];

}

function fl_widget_init() {

	if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
	return;



	function realivent_fl_widget($args)
	{

		global $wpdb;
		global $sidebar_lid;
		global $sidebar_city;
		global $sidebar_state;
		global $sidebar_zip;
		global $sidebar_showzillow;
		global $sidebar_showVT;


		//echo "sidebar_lid="; echo $sidebar_lid; echo "<br>";

		if($sidebar_lid == "")
		{
			//echo "realivent_SPW="; echo get_option('realivent_SPW_listing'); echo "<br>";

			get_featured_listings_id(get_option('realivent_SPW_listing'));
		}

		$post_name = get_query_var('name');
		$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");
		//$bloginfo_url = bloginfo('url');

		$bloginfo_url = get_option('siteurl');

		//$query = "SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'";
		//echo "query="; echo $query; echo "<br>";

		//echo "post_name="; echo $post_name; echo "<br>";

		//echo "sidebarid="; echo "<br>"; echo $sidebar_lid;;

		global $wpdb;
		$post_name = get_query_var('name');
		$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");

		$fl_owner = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");

		$this_site_type = get_option('site_type');

		//echo "this site type = ".$this_site_type."<br>";
		//echo "this page type = ".$post_name."<br>";
		//echo "FL page url = ".$fl_url."<br>";


		if($sidebar_lid != '')
		{
			if($this_site_type == 'Full_Website')
			{
				if($post_name == $fl_url)
				{

					//echo "<div style='clear:both'>\n";
					echo "<div style='clear:none'>\n";
					echo "<h2>Quick Links";
					echo "</h2>\n";


					echo "<table cellpadding='5px' cellspacing='5px' width='99%' border='0' bgcolor='#FFFFFF' style='border:1px solid #999999; font-size:12px;'>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='95%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\" align\"right\">Neighborhood Information</a></td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/reviews_sm.png\" border=\"0\" /></a></td><td width='95%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\">Points of Interest and Reviews</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					if($sidebar_showzillow == '1')
					{
						echo "<tr>\n";
						echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/comps_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;zillow_comps=true&amp;show=false&amp;all=true\">Comparables and Price Trends</a></td>\n";
						echo "</td>\n";
						echo "</tr>\n";
					}

					if($sidebar_showVT != '')
					{

						$vt_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Virtual_Tour_Page_ID') ."'");

						if($vt_url == '')
						{

							$vt_page_content = "<iframe src='".urldecode($sidebar_showVT)."' align='left' frameborder='0' height='800' width='900'></iframe>";

							$clean_vt_content = addslashes($vt_page_content);

							$wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_name, post_modified, post_modified_gmt, guid, post_type, post_status) values('".$fl_owner."', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".addslashes($vt_page_content)."', 'virtual-tour', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".get_option('siteurl')."/virtual-tour/', 'page', 'publish')");
							$vt_id = $wpdb->insert_id;
							update_option('Virtual_Tour_Page_ID', $vt_id);
							$wpdb->query("INSERT INTO $wpdb->postmeta (meta_key, meta_value, post_id) values ('_wp_page_template', 'page_no_sidebar.php', '".$vt_id."')");

							//$wpdb->query("UPDATE $wpdb->posts SET post_content = '".addslashes($vt_page_content)."' where post_name = 'virtual-tour' and ID = '".$vt_id."' ");

							wp_update_post(array('post_status' => 'publish', 'post_type' => 'page', 'ID' => $vt_id, 'post_name' => 'virtual-tour', 'post_content' => $clean_vt_content ));

						}
						else
						{
							$vt_page_content = "<iframe src='".urldecode($sidebar_showVT)."' align='left' frameborder='0' height='800' width='900'></iframe>";


							$vt_id = get_option('Virtual_Tour_Page_ID');

							$wpdb->query("UPDATE $wpdb->posts SET post_content = '".addslashes($vt_page_content)."' where post_name = 'virtual-tour' and ID = '".$vt_id."' ");



						}
						echo "<tr>\n";
						//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/virtualtour_sm.png\" border=\"0\" /></a></td><td width='33%'><a target='_blank' href='".urldecode($sidebar_showVT)."'>Property Virtual Tour</a></td>";

						echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/virtualtour_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$vt_url\">Property Virtual Tour</a></td>\n";

						echo "</td>\n";
						echo "</tr>\n";

					}

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds2_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;map=true&amp;show=false&amp;all=true\">View Map</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;birdseye=true&amp;show=false&amp;all=true\">Bird's Eye View</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a target='_blank' href=\"http://nces.ed.gov/globallocator/index.asp?search=1&State=$sidebar_state&city=$sidebar_city&zipcode=sidebar_zip&miles=&itemname=&soryby=city&School=1&PrivSchool=1&College=1&Library=1&Status=Search+Finished&Records=0\">Area Schools</a></td>\n";

					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;areaschools=true&amp;show=false&amp;all=true\">Area Schools</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='33%'><a target='_blank' href=\"http://www.realivent.com/email_friend_cl.php?listing_id=$sidebar_lid\">Email to Friend</a></td>";

					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;emailfriend=true&amp;show=false&amp;all=true\">Email to Friend</a></td>\n";

					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;more_info=true&amp;show=false&amp;all=true\">Request More Information</a>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/requestinfo_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;showing=true&amp;show=false&amp;all=true\">Schedule a Showing</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/calculator_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;calculator=true&amp;show=false&amp;all=true\">Calculate Payment</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"http://realivent.com/poster/account/download_pdf.php?listing_id=$sidebar_lid\"><img src=\"http://www.realivent.com/graphics/flwidget/pdf-icon.png\" border=\"0\" /></a></td><td width='28%'><a href=\"http://realivent.com/poster/account/download_pdf.php?listing_id=$sidebar_lid\">Print PDF</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "</table>\n";

					echo "</div>\n";
					echo "<br>\n";
					echo "<br>\n";
				}
			}
			else
			{
				if($post_name == $fl_url || $post_name == '')
				{

					//echo "<div style='clear:both'>\n";
					echo "<div style='clear:none'>\n";
					echo "<h2>Quick Links";
					echo "</h2>\n";


					echo "<table cellpadding='5px' cellspacing='5px' width='99%' border='0' bgcolor='#FFFFFF' style='border:1px solid #999999; font-size:12px;'>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='95%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\" align\"right\">Neighborhood Information</a></td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/reviews_sm.png\" border=\"0\" /></a></td><td width='95%' align='left'>
		<a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;yelp_reviews=true&amp;show=false&amp;all=true\">Points of Interest and Reviews</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					if($sidebar_showzillow == '1')
					{
						echo "<tr>\n";
						echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/comps_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;zillow_comps=true&amp;show=false&amp;all=true\">Comparables and Price Trends</a></td>\n";
						echo "</td>\n";
						echo "</tr>\n";
					}

					if($sidebar_showVT != '')
					{


						$vt_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Virtual_Tour_Page_ID') ."'");

						if($vt_url == '')
						{

							$vt_page_content = "<iframe src='".urldecode($sidebar_showVT)."' align='left' frameborder='0' height='800' width='900'></iframe>";

							$clean_vt_content = addslashes($vt_page_content);

							$wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content,  post_name, post_modified, post_modified_gmt, guid, post_type, post_status) values('".$fl_owner."', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".addslashes($vt_page_content)."', 'virtual-tour', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".get_option('siteurl')."/virtual-tour/', 'page', 'publish')");
							$vt_id = $wpdb->insert_id;
							update_option('Virtual_Tour_Page_ID', $vt_id);
							$wpdb->query("INSERT INTO $wpdb->postmeta (meta_key, meta_value, post_id) values ('_wp_page_template', 'page_no_sidebar.php', '".$vt_id."')");

							//$wpdb->query("UPDATE $wpdb->posts SET post_content = '".addslashes($vt_page_content)."' where post_name = 'virtual-tour' and ID = '".$vt_id."' ");

							wp_update_post(array('post_status' => 'publish', 'post_type' => 'page', 'ID' => $vt_id, 'post_name' => 'virtual-tour', 'post_content' => $clean_vt_content ));

						}
						else
						{
							$vt_page_content = "<iframe src='".urldecode($sidebar_showVT)."' align='left' frameborder='0' height='800' width='900'></iframe>";

							$vt_id = get_option('Virtual_Tour_Page_ID');

							//$wpdb->query("UPDATE $wpdb->posts SET (post_author, post_date, post_date_gmt, post_content, post_name, post_modified, post_modified_gmt, guid, post_type) values('".$fl_owner."', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".addslashes($vt_page_content)."', 'virtual-tour', '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."', '".get_option('siteurl')."/virtual-tour/', 'page') where post_name = 'virtual_tour' and ID = '".$vt_id."' ");

							$wpdb->query("UPDATE $wpdb->posts SET post_content = '".addslashes($vt_page_content)."' where post_name = 'virtual-tour' and ID = '".$vt_id."' ");


						}
						echo "<tr>\n";
						//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/virtualtour_sm.png\" border=\"0\" /></a></td><td width='33%'><a target='_blank' href='".urldecode($sidebar_showVT)."'>Property Virtual Tour</a></td>";

						echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/virtualtour_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$vt_url\">Property Virtual Tour</a></td>\n";

						echo "</td>\n";
						echo "</tr>\n";


					}

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds2_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;map=true&amp;show=false&amp;all=true\">View Map</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/birds_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;birdseye=true&amp;show=false&amp;all=true\">Bird's Eye View</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a target='_blank' href=\"http://nces.ed.gov/globallocator/index.asp?search=1&State=$sidebar_state&city=$sidebar_city&zipcode=sidebar_zip&miles=&itemname=&soryby=city&School=1&PrivSchool=1&College=1&Library=1&Status=Search+Finished&Records=0\">Area Schools</a></td>\n";

					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/schools_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;areaschools=true&amp;show=false&amp;all=true\">Area Schools</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					//echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='33%'><a target='_blank' href=\"http://www.realivent.com/email_friend_cl.php?listing_id=$sidebar_lid\">Email to Friend</a></td>";

					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/email_sm.png\" border=\"0\" /></a></td><td width='28%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;emailfriend=true&amp;show=false&amp;all=true\">Email to Friend</a></td>\n";

					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/neighborhoodinfo_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;more_info=true&amp;show=false&amp;all=true\">Request More Information</a>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/requestinfo_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;showing=true&amp;show=false&amp;all=true\">Schedule a Showing</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;neighborhood=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/calculator_sm.png\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;calculator=true&amp;show=false&amp;all=true\">Calculate Payment</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					$wp_user = get_option('fl_realivent_username');
					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"http://realivent.com/poster/account/download_pdf.php?wp_user=$wp_user&listing_id=$sidebar_lid\"><img src=\"http://www.realivent.com/graphics/flwidget/pdf-icon.png\" border=\"0\" /></a></td><td width='28%'><a href=\"http://realivent.com/poster/account/download_pdf.php?wp_user=$wp_user&listing_id=$sidebar_lid\">Print PDF</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;qr_code=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/qr_code.jpg\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;qr_code=true&amp;show=false&amp;all=true\">QR Code</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					echo "<tr>\n";
					echo "<td width='5%' align='left'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;street_view=true&amp;show=false&amp;all=true\"><img src=\"http://www.realivent.com/graphics/flwidget/street_view.jpg\" border=\"0\" /></a></td><td width='33%'><a href=\"$bloginfo_url/$fl_url?listing_id=$sidebar_lid;&amp;street_view=true&amp;show=false&amp;all=true\">Street View</a></td>\n";
					echo "</td>\n";
					echo "</tr>\n";

					$url = "http://realivent.com/accounts/walkscore.php?listing_id=$sidebar_lid&wp_user=$wp_user";
					$result = file_get_contents($url);
					$obj = json_decode($result);
					if((int)$obj->status == 1) {
						echo "<tr>\n";
						echo "<td width='5%' align='left' colspan=2><a href=\"$obj->ws_link\"><img src=\"$obj->logo_url\" target='_blank' border=\"0\" /></a></td>\n";
						echo "</td>\n";
						echo "</tr>\n";
					}

					echo "</table>\n";

					echo "</div>\n";
					echo "<br>\n";
					echo "<br>\n";
				}
			}
		}
		extract($args);

		echo $before_widget;
		echo "<div style='text-align:center;'>".$before_title . $title . $after_title;

		//if($sidebar_lid != '')
		//{
		echo get_fl_card();
		//}

		echo "</div>".$after_widget;
	}

	function get_fl_card()
	{

		$listdata = getContentUsingCurl("http://realivent.com/services/get_featured_listings_xml.php?username=".get_option('fl_realivent_username')."&actives=true&pendings=false&solds=false",$fields);

		$p =& new xmlParser();
		$p->parse($listdata);
		$opt = $p->output;
		$listings = getSimpleArray($opt);


		global $wpdb;
		$post_name = get_query_var('name');
		$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");

		//$query = "SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'";
		//echo "query="; echo $query; echo "<br>";

		//echo "post_name="; echo $post_name; echo "<br>";

		if($post_name != $fl_url)
		{
			if(sizeof($listings))
			{
		?>
		<div style="padding-bottom:10px;">
		<table width="99%" border="0" style="border:1px solid #999999; text-align:left;" cellpadding="0" cellspacing=0>
			<tr>
				<td>
					<strong style="font-size:14px; color:#333333;">Featured Listings</strong>
				</td>
			</tr>
		  <tr>
			<td style="padding:2px; font-size:10px;">
				<?
				for($i=0;$i<sizeof($listings);$i++)
				{
					$listing = $listings[$i];
							?>
							<table width="99%"  border="0" cellspacing="0" cellpadding="0" style="padding-top:10px; ">
								<tr>
									<td colspan="2" align="center"><div style="font-size:12px; color:#333333; padding:00px 0px 0px 0px; "><?php echo $listing['STREETNUM']." ".$listing['STREETDIR']." ".$listing['STREETNAME']." ".$listing['STREETSUFFIX'] ?><br /><? echo $listing['CITY'].", ".$listing['STATE']  ?></div></td>
								</tr>
								  <tr>
									<? $image = ($listing['IMAGE'] != '')? "http://realivent.com/listing_images/t_".$listing['IMAGE'] : "http://realivent.com/listing_images/nia_thumb.gif" ?>
									<td width='99%' align="center">
									<img style="border:1px solid black;" src="<? echo $image ?>" alt="" />
									<div><?php echo $listing['BEDS'] ?> BR | <?php echo $listing['BATHSTOTAL'] ?> BA $<?php echo number_format($listing['LISTPRICE'], 0) ?></div>
									<div style="padding-right:10px;"><a href=<?php echo bloginfo('url') ?>/<?php echo $fl_url ?>/?all=true&listing_id=<?php echo $listing['OID'] ?>>More Details</a></div>

									</td>
								  </tr>
								</table>
							<?

				}
				?>
			</td>
		  </tr>
		</table>
		</div>
		<?
			}
		}
		else
		{

		}
	}

	function featured_listings_isset()
	{
		global $wpdb;
		$post_name = get_query_var('name');
		$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");
		if($post_name != $fl_url)
		return true; //show the form
		else
		return false; //hide the form

	}

	function get_listings_only()
	{

		$listdata = getContentUsingCurl("http://realivent.com/services/get_featured_listings_xml.php?username=".get_option('fl_realivent_username')."&actives=true&pendings=false&solds=false",$fields);

		$p =& new xmlParser();
		$p->parse($listdata);
		$opt = $p->output;
		$listings = getSimpleArray($opt);


		global $wpdb;
		$post_name = get_query_var('name');
		$fl_url = $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE ID = '". get_option('Featured_Listing_Page_ID') ."'");
		if($post_name != $fl_url)
		{
			if(sizeof($listings))
			{
		?>
				<?
				for($i=0;$i<sizeof($listings);$i++)
				{
					$listing = $listings[$i];
					?>
					<table width="99%"  border="0" cellspacing="0" cellpadding="0" style="padding-top:10px; ">
						<tr>
							<td colspan="2" align="center"><div style="font-size:12px; color:#333333; padding:00px 0px 0px 0px; "><?php echo $listing['STREETNUM']." ".$listing['STREETDIR']." ".$listing['STREETNAME']." ".$listing['STREETSUFFIX'] ?><br /><? echo $listing['CITY'].", ".$listing['STATE']  ?></div></td>
						</tr>
						  <tr>
							<? $image = ($listing['IMAGE'] != '')? "http://realivent.com/listing_images/t_".$listing['IMAGE'] : "http://realivent.com/listing_images/nia_thumb.gif" ?>
							<td width='99%' align="center">
							<img style="border:1px solid black;" src="<? echo $image ?>" alt="" />
							<div><?php echo $listing['BEDS'] ?> BR | <?php echo $listing['BATHSTOTAL'] ?> BA $<?php echo number_format($listing['LISTPRICE'], 0) ?></div>
							<div style="padding-right:10px;"><a href=<?php echo bloginfo('url') ?>/<?php echo $fl_url ?>/?all=true&listing_id=<?php echo $listing['OID'] ?>>More Details</a></div>

							</td>
						  </tr>
						</table>
					<?

				}

			}
		}
		else
		{
			echo "featured Listing page not created";
		}
	}


	if(get_post(get_option('Featured_Listing_Page_ID')))
	{
		register_sidebar_widget('Featured Listings', 'realivent_fl_widget');
		//register_widget_control('Realivent Calc', 'calc_control');
	}
}
add_action('plugins_loaded', 'fl_widget_init');

add_action('admin_menu', 'featured_listings_admin_menu');
add_filter('the_content', 'fl_callback', 7);


function getContentUsingCurl($url,$fields) {
	$ch = curl_init($url);
	$sendheaders = array("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",);
	curl_setopt($ch, CURLOPT_POST, 0);
	curl_setopt($ch, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
	curl_setopt($ch, CURLOPT_NOBODY, 0); // set to 1 to eliminate body info from response
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
	curl_setopt($ch, CURLOPT_HTTPHEADER, $sendheaders);
	//curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // use HTTP POST to send form data

	$resp = curl_exec($ch); //execute post and get results
	curl_close ($ch);
	return $resp;

}

function getSimpleArray($opt) {
	$entries = $opt[0][child];
	$listingsarray = array();

	for($i=0;$i<sizeof($entries);$i++) {
		$entry = $entries[$i][child];
		$listingsarray[$i]=array();
		for($j=0;$j<sizeof($entry);$j++)
		{
			$item = $entry[$j];



			if(is_array($item[child]))
			$listingsarray[$i][$item[name]] = $item[child];
			else
			$listingsarray[$i][$item[name]] = $item[content];




		}

	}
	return $listingsarray;
}

function convertIndexToKey($evt) {
	$retarray = array();
	for($i=0;$i<sizeof($evt);$i++) {
		$retarray[$evt[$i][name]] = $evt[$i][content];
	}
	return $retarray;

}

?>